﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Amib.Threading;
using Top.Api.Domain;

namespace DSAClient.Core
{

    /// <summary>
    /// 七牛图片上传管理类
    /// </summary>
    public class QiniuUploadTaskManager
    {
        private bool _stop;

        public void Stop()
        {
            _stop = true;
        }

        public void Run(List<string> imagePaths, string oid, int thread)
        {
            _stop = false;

            STPStartInfo stpStartInfo = new STPStartInfo();
            stpStartInfo.IdleTimeout = 2000;
            stpStartInfo.MaxWorkerThreads = thread;
            stpStartInfo.MinWorkerThreads = 1;

            SmartThreadPool smartThreadPool = new SmartThreadPool(stpStartInfo);
            List<IWorkItemResult> tasks = new List<IWorkItemResult>();
            List<QiniuUploadTask> taskHandels = new List<QiniuUploadTask>();

            foreach (var path in imagePaths)
            {
                QiniuUploadTask task = new QiniuUploadTask(path, oid);
                tasks.Add(smartThreadPool.QueueWorkItem(new WorkItemCallback(task.Run)));
                Thread.Sleep(10);
            }
          

            smartThreadPool.Start();
            while (true)
            {
                if (_stop)
                {
                    foreach (var item in taskHandels)
                    {
                        item.Stop();
                    }
                    break;
                }
                if (smartThreadPool.IsIdle)
                {
                    break;
                }
                Thread.Sleep(50);
            }

            //判断是否全陪处理完成.
            smartThreadPool.Shutdown();
        }
    }
}
